<template>
  <div class="resizable-container"
       :class="{ selected: isSelected }"
       :style="containerStyle"
       @mousedown.stop="handleContainerMouseDown">
    <slot></slot>
    
    <!-- 调整手柄 -->
    <div v-show="isSelected" class="resize-handles">
      <div v-for="handle in resizeHandles" 
           :key="handle"
           :class="['resize-handle', handle]"
           @mousedown.stop="startResize($event, handle)">
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="component-actions" v-show="isSelected">
      <i class="fas fa-arrows-alt handle" @mousedown.stop="startDrag"></i>
      <i class="fas fa-copy" @click.stop="$emit('duplicate')"></i>
      <i class="fas fa-trash" @click.stop="$emit('delete')"></i>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  component: {
    type: Object,
    required: true
  },
  isSelected: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update', 'select', 'duplicate', 'delete'])

// 拖拽状态
const isDragging = ref(false)
const dragStartPos = ref({ x: 0, y: 0 })

// 容器样式
const containerStyle = computed(() => ({
  width: `${props.component.width}px`,
  height: `${props.component.height}px`,
  transform: `translate(${props.component.x}px, ${props.component.y}px)`
}))

// 调整手柄列表
const resizeHandles = [
  'top-left', 'top', 'top-right',
  'right', 'bottom-right', 'bottom',
  'bottom-left', 'left'
]

// 处理容器点击
const handleContainerMouseDown = (event) => {
  // 如果点击的是操作按钮或调整手柄，不处理
  if (event.target.closest('.component-actions') || event.target.closest('.resize-handles')) {
    return
  }
  
  emit('select')
  
  // 如果按住了Alt键，开始拖动
  if (event.altKey) {
    startDrag(event)
  }
}

// 开始拖拽
const startDrag = (event) => {
  event.preventDefault()
  event.stopPropagation()
  
  isDragging.value = true
  dragStartPos.value = {
    x: event.clientX - props.component.x,
    y: event.clientY - props.component.y
  }
  
  window.addEventListener('mousemove', handleDrag)
  window.addEventListener('mouseup', stopDrag)
}

// 处理拖拽
const handleDrag = (event) => {
  if (!isDragging.value) return
  
  event.preventDefault()
  event.stopPropagation()
  
  // 计算新位置（网格对齐）
  const newX = Math.round((event.clientX - dragStartPos.value.x) / 20) * 20
  const newY = Math.round((event.clientY - dragStartPos.value.y) / 20) * 20
  
  // 更新组件位置
  emit('update', {
    ...props.component,
    x: Math.max(0, newX),
    y: Math.max(0, newY)
  })
}

// 停止拖拽
const stopDrag = (event) => {
  if (event) {
    event.preventDefault()
    event.stopPropagation()
  }
  
  isDragging.value = false
  window.removeEventListener('mousemove', handleDrag)
  window.removeEventListener('mouseup', stopDrag)
}

// 开始调整大小
const startResize = (event, handle) => {
  event.preventDefault()
  event.stopPropagation()
  
  const startPos = {
    x: event.clientX,
    y: event.clientY
  }
  const startSize = {
    width: props.component.width,
    height: props.component.height
  }
  const startCoord = {
    x: props.component.x,
    y: props.component.y
  }
  
  const handleResize = (e) => {
    e.preventDefault()
    e.stopPropagation()
    
    const dx = Math.round((e.clientX - startPos.x) / 20) * 20
    const dy = Math.round((e.clientY - startPos.y) / 20) * 20
    
    const minWidth = 100
    const minHeight = 100
    const newSize = { ...startSize }
    const newCoord = { ...startCoord }
    
    switch (handle) {
      case 'top-left':
        newSize.width = Math.max(minWidth, startSize.width - dx)
        newSize.height = Math.max(minHeight, startSize.height - dy)
        newCoord.x = startCoord.x + (startSize.width - newSize.width)
        newCoord.y = startCoord.y + (startSize.height - newSize.height)
        break
      case 'top':
        newSize.height = Math.max(minHeight, startSize.height - dy)
        newCoord.y = startCoord.y + (startSize.height - newSize.height)
        break
      case 'top-right':
        newSize.width = Math.max(minWidth, startSize.width + dx)
        newSize.height = Math.max(minHeight, startSize.height - dy)
        newCoord.y = startCoord.y + (startSize.height - newSize.height)
        break
      case 'right':
        newSize.width = Math.max(minWidth, startSize.width + dx)
        break
      case 'bottom-right':
        newSize.width = Math.max(minWidth, startSize.width + dx)
        newSize.height = Math.max(minHeight, startSize.height + dy)
        break
      case 'bottom':
        newSize.height = Math.max(minHeight, startSize.height + dy)
        break
      case 'bottom-left':
        newSize.width = Math.max(minWidth, startSize.width - dx)
        newSize.height = Math.max(minHeight, startSize.height + dy)
        newCoord.x = startCoord.x + (startSize.width - newSize.width)
        break
      case 'left':
        newSize.width = Math.max(minWidth, startSize.width - dx)
        newCoord.x = startCoord.x + (startSize.width - newSize.width)
        break
    }
    
    emit('update', {
      ...props.component,
      ...newSize,
      ...newCoord
    })
  }
  
  const stopResize = (e) => {
    if (e) {
      e.preventDefault()
      e.stopPropagation()
    }
    window.removeEventListener('mousemove', handleResize)
    window.removeEventListener('mouseup', stopResize)
  }
  
  window.addEventListener('mousemove', handleResize)
  window.addEventListener('mouseup', stopResize)
}
</script>

<style scoped>
.resizable-container {
  position: absolute;
  background-color: var(--theme-container-bg, #ffffff);
  border: 1px solid var(--theme-border-color, #e2e8f0);
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  user-select: none;
  touch-action: none;
}

.resizable-container.selected {
  z-index: 100;
  border-color: var(--theme-primary-color, #3b82f6);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.component-actions {
  position: absolute;
  top: -30px;
  right: 0;
  display: flex;
  gap: 8px;
  padding: 4px;
  background-color: var(--theme-container-bg, #ffffff);
  border: 1px solid var(--theme-border-color, #e2e8f0);
  border-radius: 4px;
}

.component-actions i {
  padding: 4px;
  cursor: pointer;
  color: var(--theme-text-color, #64748b);
}

.component-actions i:hover {
  color: var(--theme-primary-color, #3b82f6);
}

.component-actions .handle {
  cursor: move;
}

.resize-handles {
  position: absolute;
  inset: 0;
  pointer-events: none;
}

.resize-handle {
  position: absolute;
  width: 8px;
  height: 8px;
  background-color: #fff;
  border: 1px solid var(--theme-primary-color, #3b82f6);
  pointer-events: all;
  z-index: 1;
}

.resize-handle.top-left {
  top: -4px;
  left: -4px;
  cursor: nw-resize;
}

.resize-handle.top {
  top: -4px;
  left: 50%;
  transform: translateX(-50%);
  cursor: n-resize;
}

.resize-handle.top-right {
  top: -4px;
  right: -4px;
  cursor: ne-resize;
}

.resize-handle.right {
  top: 50%;
  right: -4px;
  transform: translateY(-50%);
  cursor: e-resize;
}

.resize-handle.bottom-right {
  bottom: -4px;
  right: -4px;
  cursor: se-resize;
}

.resize-handle.bottom {
  bottom: -4px;
  left: 50%;
  transform: translateX(-50%);
  cursor: s-resize;
}

.resize-handle.bottom-left {
  bottom: -4px;
  left: -4px;
  cursor: sw-resize;
}

.resize-handle.left {
  top: 50%;
  left: -4px;
  transform: translateY(-50%);
  cursor: w-resize;
}
</style> 